<?php
declare(strict_types=1);

namespace Modules\Production\Http\Controllers;

use Catch\Base\CatchController as Controller;
use App\Services\RedisLockService;
use Modules\Production\Models\ProductionReportOrder;
use Illuminate\Http\Request;
use Modules\Production\Repository\ProductionReportOrderRepository;


class ProductionReportOrderController extends Controller
{
    public function __construct(
        protected readonly ProductionReportOrder $model
    ){}

    /**
     * @param Request $request
     * @return mixed
     */
    public function index(): mixed
    {
        return $this->model->getList();
    }

    /**
     * 生产汇报提交
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $postData = $request->post();
        if(!isset($postData['production_id']) || empty($postData['production_id'])){
            throw new \Exception('请求数据有误');
        }

        $key = 'SCHB_SUBMIT_' . $postData['production_id'];
        $lock = new RedisLockService($key);

        if(!$lock->lock()){
            throw new \Exception('生产汇报提交处理中，请稍后重试');
        }

        try{
            return ProductionReportOrderRepository::storeBy($postData);
        }catch (\Exception $e){
            throw $e;
        } finally {
            $lock->unlock();
        }

    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        return $this->model->firstBy($id);
    }

    /**
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update($id, Request $request)
    {
        return $this->model->updateBy($id, $request->all());
    }

    /**
     * 生产汇报删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        return ProductionReportOrderRepository::deleteBy($id);
    }

    /**
     * 工单号扫描
     * @param Request $request
     */
    public function checkProduction(Request $request)
    {
        return ProductionReportOrderRepository::checkProductionOrder($request->get('fbillno'));
    }
}
